<template>
  <div class="my_music_container padd100">
    <el-row :gutter="20">
      <el-col :lg="5">
        <div style="overflow:hidden">
          <el-menu default-active="0-0" :default-openeds="[0]" @select="select">
            <!-- sublist -->
            <el-menu-item :index="menu.index" v-for="menu in menuList" :key="menu.index">
              <span>{{ menu.title }}({{ menu.data.count }})</span>
            </el-menu-item>
            <!-- menus -->
            <el-sub-menu :index="index.toString()" v-for="(menu, index) in menus" :key="index">
              <template #title>
                <span>{{ menu.title }}({{ menu.subMenus.length }})</span>
                <el-button style="margin-left: 5px" size="small" v-if="index === 0" @click.stop="addSingSheet">新建
                </el-button>
              </template>
              <el-menu-item :index="index + '-' + key" v-for="(subMenu, key) in menu.subMenus"
                @click="(e) => menuClick(e,subMenu)">
                <div class="menu_item_box">
                  <img :src="subMenu.coverImgUrl" alt="" />
                  <div class="menu_item_text">
                    <div class="title text_ellipsis">{{ index + '-' + key === "0-0" ? "我喜欢的音乐" : subMenu.name }}</div>
                    <div class="text_box">
                      <span class="text_ellipsis">
                        {{ subMenu.trackCount }}首
                        <span v-if="subMenu.tags.length > 0">
                          by {{ subMenu.creator.nickname }}</span>
                      </span>
                      <el-icon :size="14" color="#333" v-if="index || key" @click.stop="delSingSheet(subMenu.id)">
                        <DeleteFilled />
                      </el-icon>
                    </div>
                  </div>
                </div>
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </div>
      </el-col>
      <el-col :lg="19">
        <!-- 歌手 -->
        <div class="singer_detail_container" v-if="menuIndex === '-1'">
          <div class="top_b_m_tit">
            我的歌手（{{ sublist[0].data.count }}）
          </div>
          <div class="singer_list" v-for="(item, index) in sublist[0].data.data" :key="index">
            <img class="cursor_class" :src="item.picUrl" @click="router.push('/discover/artist-detail/' + item.id)" />
            <div class="r_context">
              <el-link :href="'/discover/artist-detail/' + item.id">{{ item.name }}</el-link>
              <div class="context">
                {{ item.albumSize }}个专辑&nbsp;&nbsp;&nbsp;&nbsp;{{ item.mvSize }}个MV
              </div>
            </div>
          </div>
        </div>
        <!-- 视频 -->
        <div class="mv_detail_container" v-if="menuIndex === '-2'">
          <div class="top_b_m_tit">
            我的视频（{{ sublist[1].data.count }}）
          </div>
          <el-row :gutter="20">
            <el-col :lg="4" :sm="6" :md="6" :xs="12" style="margin:10px 0" v-for="(item,index) in sublist[1].data.data"
              :key="index">
              <Mv :picUrl="item.coverUrl" :name="item.title" :id="item.vid" :singers="item.creator"
                :playTime="item.playTime" :durationms="item.durationms" />
            </el-col>
          </el-row>
        </div>
        <!-- 歌单 -->
        <div class="music_detail_container" v-else>
          <div class="top_music_info">
            <div class="left_music_info_img">
              <img :src="playlistDetail.coverImgUrl" alt="" />
            </div>
            <div class="right_music_opeation">
              <div class="r_m_tit">
                <el-tag>歌单</el-tag>
                {{ playlistDetail.name }}
              </div>
              <p class="r_m_context">
                <img class="cursor_class" :src="playlistDetail.avatarUrl" alt="" />
                <el-link type="primary">{{ playlistDetail.nickname }}</el-link>
                <span>{{dayjs(playlistDetail.createTime).format('YYYY-MM-DD')}} 创建</span>
              </p>
              <div class="r_m_opea">
                <el-button type="primary" :icon="VideoPlay" @click="play">播放</el-button>
                <el-button type="primary" :icon="Plus" @click="addPlayList">添加到播放列表</el-button>
                <!-- <el-button type="primary" :icon="FolderAdd">收藏</el-button> -->
                <el-button :icon="Comment" @click="handleClickScrollToComment">评论 <span
                    v-if="playlistDetail.commentCount>0"> ({{playlistDetail.commentCount}})</span></el-button>
              </div>
            </div>
          </div>
          <div class="bottom_music_list">
            <div class="top_b_m_tit">
              <div class="left_tit">
                <div>歌曲列表</div>
                <span>{{ playlistDetail.trackCount }}首歌</span>
              </div>
              <div class="right_play_count">
                <span>播放：<span>{{ playlistDetail.playCount }}</span>次</span>
              </div>
            </div>
            <div>
              <MusicTable :tracks="playlistDetail.tracks" :user-id="playlistDetail.userId"
                :play-list-id="playlistDetail.id" deletedBtn />
            </div>
            <!-- 评论 -->
            <div id="comment">
              <div class="top_b_m_tit" style="margin-top:50px">
                <div class="left_tit">
                  <div>评论</div>
                  <span>共{{ playlistDetail.commentCount }}条评论</span>
                </div>
              </div>
              <CommentComponent :id="songSheet" :playlistLimit="page.pageSize" :pageNum="page.pageNum"
                @getTotal="getTotal"></CommentComponent>
              <div class="pageination_center" style="margin-top:40px">
                <el-pagination v-show="page.total > 0" v-model:currentPage="page.pageNum" :page-size="page.pageSize"
                  background layout="prev, pager, next" :total="page.total" @current-change="handleCurrentChange" />
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <Collection @handleAddSuccess="init" ref="collectionRef" />
    <el-backtop :right="100" :bottom="100" />
  </div>
</template>

<script lang="ts" setup>
import * as myMusicApi from '@/api/my-music'
import {
  Plus,
  VideoPlay,
  DocumentAdd,
  Comment,
  FolderAdd,
  DeleteFilled,
  Edit,
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import CommentComponent from "@/components/Comment/index"
import Collection from "@/components/Collection/index"
import Mv from "@/components/Mv/index"
import { reactive, ref, getCurrentInstance, computed, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import MusicTable from "@/components/MusicTable";
import dayjs from "dayjs";
import { collectionTypeRef } from "@/types/collection";
import { useStore } from "vuex";
const { proxy }: any = getCurrentInstance()
const store = useStore();
const router = useRouter()
const menuIndex = ref("0-0")
const sublist = reactive<Array<any>>([
  {
    title: '我的歌手',
    index: "-1",
    data: {}
  },
  {
    title: '我的视频',
    index: "-2",
    data: {}
  }
])
const menus = reactive<Array<any>>([
  {
    title: '创建的歌单',
    subMenus: [],
  },
  {
    title: '收藏的歌单',
    subMenus: [],
  },
])
const playlistDetail = reactive({
  id: 0,
  userId: 0,
  coverImgUrl: '',
  name: '',
  avatarUrl: '',
  nickname: '',
  createTime: '',
  trackCount: 0,
  playCount: 0,
  commentCount: 0,
  tracks: []
})
const songSheet = ref(0)
const page = reactive({
  total: 0, // 总页数
  pageNum: 1, // 当前页数
  pageSize: 20 // 每页显示多少条
})
const userId = ref(0)
const collectionRef = ref<collectionTypeRef | null>(null)
const init = async (id?: number) => {
  try {
    let userInfo = proxy.$getUserInfo()
    let cookie = localStorage.getItem('cookie')
    if (userInfo && cookie) {
      menus[0].subMenus = []
      menus[1].subMenus = []
      userId.value = userInfo.userId
      const data: any = await myMusicApi.artistSublist({ cookie })
      sublist[0].data = data
      const data2: any = await myMusicApi.mvSublist({ cookie })
      sublist[1].data = data2
      const data3: any = await myMusicApi.playlist({ uid: userId.value })
      data3.playlist.forEach((item: any) => {
        if (item.creator.userId === userId.value) {
          // 我创建的歌单
          menus[0].subMenus.push(item)
        } else {
          // 收藏的歌单
          menus[1].subMenus.push(item)
        }
      })
      songSheet.value = id || songSheet.value || menus[0].subMenus[0].id
      getRightInfo()
    } else {
      ElMessage({
        message: '请先登录',
        type: 'error',
      })
      router.push("/")
    }
  } catch (error) {
    router.push("/")
    console.log(error);
  }
}
const select = async (index: string, indexPath: string, item: any) => {
  menuIndex.value = index
  if (parseInt(menuIndex.value) < 0) {
    window.addEventListener('scroll', scrollbottom);  //页面加载时监听滚动事件
  } else {
    window.removeEventListener('scroll', scrollbottom);  //页面离开后销毁监听事件
  }
  // 更换菜单重置页数
  page.pageNum = 1
}
const menuClick = async (e: any, row: any) => {
  songSheet.value = row.id
  getRightInfo()
}
// 获取右侧信息
const getRightInfo = async () => {
  try {
    const data: any = await myMusicApi.detail({ id: songSheet.value })
    if (data.playlist.creator.userId === userId.value) {
      const data2: any = await myMusicApi.getsongDetail(data.playlist.trackIds.map((item: any) => item.id))
      playlistDetail.tracks = data2.songs
    } else {
      playlistDetail.tracks = data.playlist.tracks
    }
    playlistDetail.id = data.playlist.id
    playlistDetail.userId = data.playlist.creator.userId
    playlistDetail.coverImgUrl = data.playlist.coverImgUrl
    playlistDetail.name = menuIndex.value === "0-0" ? '我喜欢的音乐' : data.playlist.name
    playlistDetail.avatarUrl = data.playlist.creator.avatarUrl
    playlistDetail.nickname = data.playlist.creator.nickname
    playlistDetail.createTime = data.playlist.createTime
    playlistDetail.trackCount = data.playlist.trackCount
    playlistDetail.playCount = data.playlist.playCount
    playlistDetail.commentCount = data.playlist.commentCount
  } catch (error) {
    console.log(error);
  }
}
// 当前页改变事件
const handleCurrentChange = (val: number) => {
  page.pageNum = val
}
// 获取最新评论总数量
const getTotal = (val: number) => {
  page.total = val
}
// 点击评论跳转指定位置
const handleClickScrollToComment = () => {
  document.getElementById('comment')?.scrollIntoView()
}
// 新建歌单
const addSingSheet = () => {
  if (collectionRef.value) {
    collectionRef.value.id = 0
    collectionRef.value.isSongSheet = true
    collectionRef.value.dialogVisible = true
    collectionRef.value.init()
  }
}
// 删除歌单
const delSingSheet = async (id: number) => {
  ElMessageBox.confirm('确定删除歌单？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      let cookie = localStorage.getItem('cookie')
      await myMusicApi.playlistDelete({ id, cookie })
      ElMessage({
        message: '删除成功',
        type: 'success',
      })
    } catch (error) {
      console.log(error);
    }
  }).catch(() => {

  })
}
const scrollbottom = async () => {
  let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  let clientHeight = document.documentElement.clientHeight;
  let scrollHeight = document.documentElement.scrollHeight;
  let index = Math.abs(parseInt(menuIndex.value)) - 1
  if (scrollTop + clientHeight >= scrollHeight - 300 && sublist[index].data.hasMore) {
    sublist[index].data.hasMore = false // 防止触发多次
    let cookie = localStorage.getItem('cookie')
    let data: any = {}
    if (index === 0) {
      data = await myMusicApi.artistSublist({ cookie })
    }
    sublist[index].data.hasMore = data.data.hasMore
    sublist[index].data.data = [sublist[index].data.data, ...data.data]
    sublist[index].data.count = data.data.count
  }
}
// 过滤sublist菜单
const menuList = computed(() => {
  return sublist.filter((menu) => {
    return menu.index === '-1' || menu.data.count > 0
  })
})
// 播放
const play = () => {
  let list = filterMusicData()
  store.dispatch('playAll', { list });
}
// 添加到播放列表
const addPlayList = () => {
  let list = filterMusicData()
  store.dispatch('addList', { list });
}
// 把需要vip 或者音源不可用的过滤出去
const filterMusicData = ():any[] => {
  let list = playlistDetail.tracks.filter((item: any)=>{
    return item.fee != 1
  })
  return list
}
init()
onUnmounted(() => {
  window.removeEventListener('scroll', scrollbottom);  //页面离开后销毁监听事件
})
</script>
<style lang="scss" scoped>
.my_music_container {
  margin-top: 20px;

  .menu_item_box {
    display: flex;
    align-items: center;

    img {
      width: 40px;
      height: 40px;
      object-fit: cover;
    }

    .menu_item_text {
      display: flex;
      flex-direction: column;
      margin-left: 10px;
      font-size: 12px;

      .title {
        height: 20px;
        line-height: 20px;
        width: 110px;
      }

      .text_box {
        display: flex;
        align-items: center;

        span {
          height: 20px;
          line-height: 20px;
          width: 90px;
          // color: #999;
        }

        .el-icon {
          display: none;

          &:hover {
            color: #999;
          }
        }
      }
    }
  }

  .top_b_m_tit {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 2px solid #409eff;
    padding-bottom: 10px;
    font-size: 24px
  }

  .singer_detail_container {
    padding: 20px;

    .singer_list {
      display: flex;
      padding: 10px 0;
      border-bottom: 1px solid #ddd;

      img {
        width: 80px;
        width: 80px;
        object-fit: cover;
      }

      .r_context {
        margin-left: 15px;

        .context {
          color: #666;
          font-size: 12px;
        }
      }
    }
  }

  .mv_detail_container {
    padding: 20px;
  }

  .music_detail_container {
    padding: 20px;

    .top_music_info {
      display: flex;

      .left_music_info_img {
        width: 200px;
        height: 200px;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      .right_music_opeation {
        color: #333;
        margin-left: 30px;
        flex: 1;

        .r_m_tit {
          font-size: 20px;
        }

        .r_m_context {
          display: flex;
          align-items: center;

          img {
            height: 35px;
            width: 35px;
            margin-right: 8px;
          }

          span {
            margin-left: 15px;
            color: #999;
            font-size: 12px;
          }
        }
      }
    }

    .bottom_music_list {
      margin-top: 50px;

      .top_b_m_tit {
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 2px solid #409eff;
        padding-bottom: 10px;

        .left_tit {
          color: #333;
          font-size: 20px;
          display: flex;

          span {
            color: #666;
            font-size: 12px;
            margin-top: 10px;
            margin-left: 14px;
          }
        }

        .right_play_count {
          span {
            color: #666;
            font-size: 12px;

            span {
              color: #409eff;
              font-weight: 700;
            }
          }
        }
      }

      .music_table_container {
        a {
          color: #333;

          &:hover {
            color: #333;
          }
        }

        .music_table_index {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .el-icon {
            &:hover {
              color: #409eff;
            }
          }
        }

        .table_opeat {
          font-size: 16px;
        }
      }

      .comment_container {
        .my_comment_wrapper {
          display: flex;
          margin-top: 30px;

          .left_user_avatar {
            width: 50px;
            height: 50px;

            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
          }

          .right_text_input {
            flex: 1;
            margin-left: 14px;

            .btn_comment {
              margin-top: 10px;
              display: flex;
              justify-content: flex-end;
            }
          }
        }
      }
    }
  }
}

:deep(.el-menu-item.is-active) {
  background: #169af3;
  color: #fff !important;
}

:deep(.r_context .el-link) {
  --el-link-text-color: #333;
  --el-link-hover-text-color: #333;
  font-weight: bold;
  margin: 10px 0;
  font-size: 16px;
}

.el-menu-item {
  &:hover {
    .menu_item_box {
      .menu_item_text {
        .text_box {
          .el-icon {
            display: block;
          }
        }
      }
    }
  }
}
</style>
